import 'package:bitcoin_mine/api/api.dart';
import 'package:bitcoin_mine/common/BaseEntity.dart';
import 'package:bitcoin_mine/common/global.dart';
import 'package:bitcoin_mine/http/http_request.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../l10n/app_localizations.dart';

/// 邀请码输入对话框
class InvitationCodeDialog extends StatefulWidget {
  const InvitationCodeDialog({super.key});

  @override
  State<InvitationCodeDialog> createState() => _InvitationCodeDialogState();
}

class _InvitationCodeDialogState extends State<InvitationCodeDialog> {
  final TextEditingController _codeController = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  @override
  void dispose() {
    _codeController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  /// 粘贴邀请码
  Future<void> _pasteCode() async {
    final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
    if (clipboardData?.text != null && clipboardData!.text!.isNotEmpty) {
      _codeController.text = clipboardData.text!;
    }
  }

  /// 确认邀请码
  void _confirmCode() {
    final code = _codeController.text.trim();
    if (code.isEmpty) {
      Get.snackbar(
        '',
        AppLocalizations.of(context).enterInvitationCode,
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red.withOpacity(0.8),
        colorText: Colors.white,
      );
      return;
    }
    HttpRequest.instance.requestNetwork<BaseEntity<dynamic>>(
      Api.bindInvitationCode,
      method: "POST",
      params: {"invitation_code": code},
      onSuccess: (data) {
        Get.back(result: code);
        Global.updateMineInfo();
      },
    );
    // 关闭对话框并返回邀请码
    Get.back(result: code);
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);

    return Dialog(
      backgroundColor: Colors.transparent,
      insetPadding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/bg_area.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: ClipPath(
          clipper: _DialogClipper(),
          child: Container(
            padding: EdgeInsets.all(24.w),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题
                Text(
                  localizations.enterInvitationCode,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20.sp,
                    fontWeight: FontWeight.bold,
                  ),
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 24.h),

                // 输入框和粘贴按钮
                Container(
                  decoration: BoxDecoration(
                    color: const Color(0xFF252B4A), // 稍浅的深蓝色
                    borderRadius: BorderRadius.circular(8.r),
                    border: Border.all(
                      color: const Color(0xFF05FFFD),
                      width: 1.5.w,
                    ),
                  ),
                  child: Row(
                    children: [
                      // 输入框
                      Expanded(
                        child: TextField(
                          controller: _codeController,
                          focusNode: _focusNode,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w600,
                          ),
                          decoration: InputDecoration(
                            hintText:
                                localizations.enterInvitationCodePlaceholder,
                            hintStyle: TextStyle(
                              color: const Color(0xFF6B7FA8),
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w600,
                            ),
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.symmetric(
                              horizontal: 16.w,
                              vertical: 14.h,
                            ),
                          ),
                          textCapitalization: TextCapitalization.characters,
                        ),
                      ),

                      // 粘贴按钮
                      Container(
                        width: 80.w,
                        height: 48.h,
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            colors: [Color(0xFF05FFFD), Color(0xFF00B8D4)],
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                          ),
                          borderRadius: BorderRadius.only(
                            topRight: Radius.circular(8.r),
                            bottomRight: Radius.circular(8.r),
                          ),
                        ),
                        child: Material(
                          color: Colors.transparent,
                          child: InkWell(
                            onTap: _pasteCode,
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(8.r),
                              bottomRight: Radius.circular(8.r),
                            ),
                            child: Center(
                              child: Text(
                                localizations.paste,
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 16.h),

                // 提示文本
                Text(
                  localizations.miningSpeedRewards,
                  style: TextStyle(
                    color: const Color(0xFF05FFFD),
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                  ),
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 24.h),

                // 确认按钮
                Container(
                  width: double.infinity,
                  height: 50.h,
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      colors: [Color(0xFF05FFFD), Color(0xFF00B8D4)],
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                    ),
                    borderRadius: BorderRadius.circular(8.r),
                    border: Border.all(
                      color: const Color(0xFF05FFFD),
                      width: 1.5.w,
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: const Color(0xFF05FFFD).withOpacity(0.5),
                        blurRadius: 10.r,
                        spreadRadius: 1.r,
                      ),
                    ],
                  ),
                  child: Material(
                    color: Colors.transparent,
                    child: InkWell(
                      onTap: _confirmCode,
                      borderRadius: BorderRadius.circular(8.r),
                      child: Center(
                        child: Text(
                          localizations.confirm,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

/// 自定义裁剪器，用于创建带角的边框效果
class _DialogClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path();
    final cornerSize = 12.0;

    // 左上角切角
    path.moveTo(cornerSize, 0);
    path.lineTo(size.width - cornerSize, 0);
    // 右上角切角
    path.lineTo(size.width, cornerSize);
    path.lineTo(size.width, size.height - cornerSize);
    // 右下角切角
    path.lineTo(size.width - cornerSize, size.height);
    path.lineTo(cornerSize, size.height);
    // 左下角切角
    path.lineTo(0, size.height - cornerSize);
    path.lineTo(0, cornerSize);
    path.close();

    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}
